package com.zenithmind.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.chat.mapper.ChatFriendMapper;
import com.zenithmind.chat.mapper.ChatFriendRequestMapper;
import com.zenithmind.chat.pojo.dto.ChatFriendRequestDTO;
import com.zenithmind.chat.pojo.entity.ChatFriend;
import com.zenithmind.chat.pojo.entity.ChatFriendRequest;
import com.zenithmind.chat.pojo.vo.ChatFriendVO;
import com.zenithmind.chat.service.ChatFriendService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.exception.BusinessException;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.utils.BeanCopyUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Collectors;

/**
 * 好友关系服务实现类
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatFriendServiceImpl extends ServiceImpl<ChatFriendMapper, ChatFriend> implements ChatFriendService {

    private final ChatFriendRequestMapper friendRequestMapper;

    @Override
    public PageResult<ChatFriendVO> getFriendPage(String userId, String groupName, String keyword,
                                                 Integer pageNum, Integer pageSize) {
        // 构建查询条件
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getIsDeleted, 0);

        if (StringUtils.hasText(groupName)) {
            wrapper.eq(ChatFriend::getGroupName, groupName);
        }

        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(ChatFriend::getFriendName, keyword)
                           .or()
                           .like(ChatFriend::getRemarkName, keyword));
        }

        wrapper.orderByDesc(ChatFriend::getIsTop)
               .orderByDesc(ChatFriend::getAddTime);

        // 分页查询
        Page<ChatFriend> page = new Page<>(pageNum, pageSize);
        IPage<ChatFriend> result = page(page, wrapper);

        // 转换为VO
        List<ChatFriendVO> voList = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        return PageResult.of(voList, result.getTotal());
    }

    @Override
    public List<ChatFriendVO> getUserFriends(String userId, Integer status) {
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getIsDeleted, 0);

        if (status != null) {
            wrapper.eq(ChatFriend::getStatus, status);
        }

        wrapper.orderByDesc(ChatFriend::getIsTop)
               .orderByDesc(ChatFriend::getAddTime);

        List<ChatFriend> friends = list(wrapper);
        return friends.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public ChatFriendVO getFriendById(String userId, String friendId) {
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getFriendId, friendId)
               .eq(ChatFriend::getIsDeleted, 0);

        ChatFriend friend = getOne(wrapper);
        if (friend == null) {
            throw new BusinessException("好友不存在");
        }

        return convertToVO(friend);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String sendFriendRequest(ChatFriendRequestDTO requestDTO, String userId) {
        // 检查是否已经是好友
        if (checkIsFriend(userId, requestDTO.getTargetId())) {
            throw new BusinessException("对方已经是您的好友");
        }

        // 检查是否已发送过申请
        LambdaQueryWrapper<ChatFriendRequest> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendRequest::getRequesterId, userId)
               .eq(ChatFriendRequest::getTargetId, requestDTO.getTargetId())
               .eq(ChatFriendRequest::getStatus, 0); // 待处理

        long count = friendRequestMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("您已发送过好友申请，请等待对方处理");
        }

        // 创建好友申请
        ChatFriendRequest request = new ChatFriendRequest();
        request.setRequesterId(userId);
        request.setRequesterName(UserContext.getUsername());
        request.setRequesterAvatar(""); // TODO: 从用户服务获取
        request.setTargetId(requestDTO.getTargetId());
        request.setRequestMessage(requestDTO.getRequestMessage());
        request.setAddSource(requestDTO.getAddSource());
        request.setStatus(0); // 待处理
        request.setRequestTime(LocalDateTime.now());
        request.setExpireTime(LocalDateTime.now().plusDays(7)); // 7天过期

        friendRequestMapper.insert(request);

        log.info("用户 {} 向 {} 发送好友申请", userId, requestDTO.getTargetId());
        return request.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handleFriendRequest(String requestId, Boolean accept, String responseMessage, String userId) {
        ChatFriendRequest request = friendRequestMapper.selectById(requestId);
        if (request == null) {
            throw new BusinessException("好友申请不存在");
        }
        
        if (!Objects.equals(request.getTargetId(), userId)) {
            throw new BusinessException("无权限处理该申请");
        }
        
        if (request.getStatus() != 0) {
            throw new BusinessException("该申请已被处理");
        }
        
        if (request.getExpireTime().isBefore(LocalDateTime.now())) {
            throw new BusinessException("该申请已过期");
        }
        
        // 更新申请状态
        request.setStatus(accept ? 1 : 2);
        request.setResponseMessage(responseMessage);
        request.setResponseTime(LocalDateTime.now());
        friendRequestMapper.updateById(request);
        
        if (accept) {
            // 创建双向好友关系
            createFriendRelation(request.getRequesterId(), request.getTargetId(), 
                               request.getRequesterName(), UserContext.getUsername());
        }
        
        log.info("用户 {} {} 好友申请 {}", userId, accept ? "同意" : "拒绝", requestId);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteFriend(String friendId, String userId) {
        // 删除双向好友关系
        LambdaQueryWrapper<ChatFriend> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getFriendId, friendId);
        
        LambdaQueryWrapper<ChatFriend> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(ChatFriend::getUserId, friendId)
               .eq(ChatFriend::getFriendId, userId);
        
        boolean result1 = remove(wrapper1);
        boolean result2 = remove(wrapper2);
        
        log.info("用户 {} 删除好友 {}", userId, friendId);
        return result1 || result2;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean blockFriend(String friendId, String userId) {
        return updateFriendStatus(userId, friendId, 2); // 拉黑
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unblockFriend(String friendId, String userId) {
        return updateFriendStatus(userId, friendId, 1); // 正常
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateFriendRemark(String friendId, String remarkName, String userId) {
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getFriendId, friendId);
        
        ChatFriend friend = getOne(wrapper);
        if (friend == null) {
            throw new BusinessException("好友关系不存在");
        }
        
        friend.setRemarkName(remarkName);
        return updateById(friend);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateFriendGroup(String friendId, String groupName, String userId) {
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getFriendId, friendId);
        
        ChatFriend friend = getOne(wrapper);
        if (friend == null) {
            throw new BusinessException("好友关系不存在");
        }
        
        friend.setGroupName(groupName);
        return updateById(friend);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setFriendTop(String friendId, Boolean isTop, String userId) {
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getFriendId, friendId);
        
        ChatFriend friend = getOne(wrapper);
        if (friend == null) {
            throw new BusinessException("好友关系不存在");
        }
        
        friend.setIsTop(isTop ? 1 : 0);
        return updateById(friend);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setDisturbFree(String friendId, Boolean isDisturbFree, String userId) {
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getFriendId, friendId);
        
        ChatFriend friend = getOne(wrapper);
        if (friend == null) {
            throw new BusinessException("好友关系不存在");
        }
        
        friend.setIsDisturbFree(isDisturbFree ? 1 : 0);
        return updateById(friend);
    }

    @Override
    public List<ChatFriendVO> searchUsers(String keyword, String userId, Integer limit) {
        // TODO: 这里需要调用用户服务来搜索用户，暂时返回空列表
        // 实际实现中应该通过Feign调用用户服务的搜索接口
        return List.of();
    }

    @Override
    public List<String> getFriendGroups(String userId) {
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getIsDeleted, 0)
               .isNotNull(ChatFriend::getGroupName)
               .ne(ChatFriend::getGroupName, "")
               .groupBy(ChatFriend::getGroupName)
               .orderByAsc(ChatFriend::getGroupName);

        List<ChatFriend> friends = list(wrapper);
        return friends.stream()
                .map(ChatFriend::getGroupName)
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public Boolean checkIsFriend(String userId, String friendId) {
        // 使用MyBatis-Plus的count方法
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getFriendId, friendId)
               .eq(ChatFriend::getStatus, 1)
               .eq(ChatFriend::getIsDeleted, 0);

        return count(wrapper) > 0;
    }

    @Override
    public Boolean checkIsBlocked(String userId, String friendId) {
        // 使用MyBatis-Plus的count方法
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getFriendId, friendId)
               .eq(ChatFriend::getStatus, 2)
               .eq(ChatFriend::getIsDeleted, 0);

        return count(wrapper) > 0;
    }

    @Override
    public List<Object> getFriendRequests(String userId, String type, Integer status) {
        LambdaQueryWrapper<ChatFriendRequest> wrapper = new LambdaQueryWrapper<>();

        if ("sent".equals(type)) {
            wrapper.eq(ChatFriendRequest::getRequesterId, userId);
        } else if ("received".equals(type)) {
            wrapper.eq(ChatFriendRequest::getTargetId, userId);
        }

        if (status != null) {
            wrapper.eq(ChatFriendRequest::getStatus, status);
        }

        wrapper.orderByDesc(ChatFriendRequest::getRequestTime);

        List<ChatFriendRequest> requests = friendRequestMapper.selectList(wrapper);
        return requests.stream()
                .map(request -> (Object) BeanCopyUtils.copyBean(request, ChatFriendVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public Integer countFriends(String userId, Integer status) {
        // 使用MyBatis-Plus的count方法
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getIsDeleted, 0);

        if (status != null) {
            wrapper.eq(ChatFriend::getStatus, status);
        }

        return Math.toIntExact(count(wrapper));
    }

    // 私有方法
    private void createFriendRelation(String userId1, String userId2, String userName1, String userName2) {
        LocalDateTime now = LocalDateTime.now();
        
        // 创建用户1 -> 用户2的关系
        ChatFriend friend1 = new ChatFriend();
        friend1.setUserId(userId1);
        friend1.setFriendId(userId2);
        friend1.setFriendName(userName2);
        friend1.setStatus(1);
        friend1.setGroupName("我的好友");
        friend1.setAddTime(now);
        friend1.setAddSource("好友申请");
        
        // 创建用户2 -> 用户1的关系
        ChatFriend friend2 = new ChatFriend();
        friend2.setUserId(userId2);
        friend2.setFriendId(userId1);
        friend2.setFriendName(userName1);
        friend2.setStatus(1);
        friend2.setGroupName("我的好友");
        friend2.setAddTime(now);
        friend2.setAddSource("好友申请");
        
        save(friend1);
        save(friend2);
    }

    private Boolean updateFriendStatus(String userId, String friendId, Integer status) {
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
               .eq(ChatFriend::getFriendId, friendId);

        ChatFriend friend = getOne(wrapper);
        if (friend == null) {
            throw new BusinessException("好友关系不存在");
        }

        friend.setStatus(status);
        return updateById(friend);
    }

    /**
     * 转换为VO对象
     */
    private ChatFriendVO convertToVO(ChatFriend friend) {
        ChatFriendVO vo = BeanCopyUtils.copyBean(friend, ChatFriendVO.class);

        // 设置显示名称（备注名称优先）
        vo.setDisplayName(StringUtils.hasText(friend.getRemarkName()) ?
                         friend.getRemarkName() : friend.getFriendName());

        // 设置状态文本
        switch (friend.getStatus()) {
            case 1:
                vo.setStatusText("正常");
                break;
            case 2:
                vo.setStatusText("已拉黑");
                break;
            default:
                vo.setStatusText("未知");
        }

        // 设置在线状态（这里可以通过Redis或其他方式获取实时状态）
        vo.setIsOnline(false); // 默认离线

        // 设置未读消息数（这里可以通过查询私聊消息表获取）
        vo.setUnreadCount(0); // 默认0

        return vo;
    }
}
